# !/usr/bin/env python
# -*- coding: utf-8 -*-
# @File  : 高斯核RBF.py
# @Author: dongguangwen
# @Date  : 2025-02-15 17:51
import numpy as np
import matplotlib.pyplot as plt
from sklearn.datasets import make_moons
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.svm import SVC

# 1.获取数据
x, y = make_moons(noise=0.15, random_state=22)


# 数据可视化展示
# plt.scatter(x[y == 0, 0], x[y == 0, 1])
# plt.scatter(x[y == 1, 0], x[y == 1, 1])
# plt.show()


# 构建函数
def RBFsvm(gamma=0.01):
    return Pipeline(
        [
            ('std_scaler', StandardScaler()),
            ('svm', SVC(kernel='rbf', gamma=gamma))
        ]
    )


# 绘制决策边界
def plot_decision_boundary(model, axis):
    x0, x1 = np.meshgrid(
        np.linspace(axis[0], axis[1], int((axis[1] - axis[0]) * 100)).reshape(-1, 1),
        np.linspace(axis[2], axis[3], int((axis[3] - axis[2]) * 100)).reshape(-1, 1)
    )
    X_new = np.c_[x0.ravel(), x1.ravel()]
    y_predict = model.predict(X_new)
    zz = y_predict.reshape(x0.shape)

    from matplotlib.colors import ListedColormap
    custom_map = ListedColormap(["#EF9A9A", "#FFF59D", "#90CAF9"])

    # plt.contourf(x0,x1,zz,linewidth=5,cmap=custom_map)
    plt.contourf(x0, x1, zz, cmap=custom_map)


# 模型训练
svc1 = RBFsvm(gamma=1.0)
svc1.fit(x, y)

plot_decision_boundary(svc1, axis=[-1.5, 2.5, -1, 1.5])
plt.scatter(x[y == 0, 0], x[y == 0, 1])
plt.scatter(x[y == 1, 0], x[y == 1, 1])
plt.show()

svc2 = RBFsvm(100)
svc2.fit(x, y)
plot_decision_boundary(svc2, axis=[-1.5, 2.5, -1, 1.5])
plt.scatter(x[y == 0, 0], x[y == 0, 1])
plt.scatter(x[y == 1, 0], x[y == 1, 1])
plt.show()

svc3 = RBFsvm(0.1)
svc3.fit(x, y)
plot_decision_boundary(svc3, axis=[-1.5, 2.5, -1, 1.5])
plt.scatter(x[y == 0, 0], x[y == 0, 1])
plt.scatter(x[y == 1, 0], x[y == 1, 1])
plt.show()
